import axios from 'axios';

// import qs from 'qs'
import Message from 'vue-m-message';
import useUserStore from '@/store/modules/user';

const api = axios.create({
  baseURL:
    import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true'
      ? '/proxy/'
      : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 1000 * 60,
  responseType: 'json',
});

api.interceptors.request.use(request => {
  // 全局拦截请求发送前提交的参数
  const userStore = useUserStore();

  // 设置请求头
  if (request.headers) {
    if (userStore.isLogin) {
      request.headers.Token =
        request.headers.Authorization = `Bearer ${userStore.token}`;
    }
  }
  try {
    if (!request.data) {
      request.data = {};
    }
    // 设置请求头
    // 设备类型 0-pc 1-android 2-ios 3-微信
    request.data.deviceType = 0;
    // 平台类型不能为空 0-学生端 1-机构端 2-平台端
    if (request.data.platType === undefined && userStore.platType) {
      request.data.platType = userStore.platType;
    }
  } catch (e) {
    console.error('--->:', e);
  }
  // 是否将 POST 请求参数进行字符串化处理
  if (request.method === 'post') {
    // request.data = qs.stringify(request.data, {
    //   arrayFormat: 'brackets',
    // })
  }
  return request;
});

api.interceptors.response.use(
  response => {
    if (response.data instanceof Blob) {
      return response.data;
    }
    let { body, code, message } = response.data || {};
    if (code == 200) {
      return body;
    } else {
      if (message) {
        Message.error(message, {
          zIndex: 20000,
        });
      }

      if (code == 1001) {
        useUserStore().logout();
      }
      throw response.data;
    }
  },
  error => {
    let message = error.message;
    if (message === 'Network Error') {
      message = '后端网络故障';
    } else if (message.includes('timeout')) {
      message = '接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`;
    }
    Message.error(message, {
      zIndex: 20000,
    });
    return Promise.reject(error);
  }
);

export default api;
